[백준]단계별풀이_스택


10828번 : 스택

import sys

n = int(sys.stdin.readline())
stack = [0]
for i in range(n):
    input = sys.stdin.readline().split()
    if input[0] == "push":
        stack.append(int(input[1]))
    elif input[0] == "top":
        if len(stack) == 1:
            print(-1)
        else:
            print(stack[-1])
    elif input[0] == "size":
        if len(stack) == 1:
            print(0)
        else:
            print(len(stack)-1)
    elif input[0] == "empty":
        if len(stack) == 1:
            print(1)
        else:
            print(0)
    elif input[0] == "pop":
        if len(stack) == 1:
            print(-1)
        else:
            print(stack[-1])
        if len(stack) == 1:
            pass
        else:
            stack.pop()

IndexError 방지를 위한 초기에 0 index 추가

10773번: 제로

import sys

n = int(sys.stdin.readline())
stack = [0]
for i in range(n):
    input = int(sys.stdin.readline())
    stack.append(input)
    if input == 0:
        if len(stack) == 1:
            pass
        # 위에서 input 값이 0일 경우에도 삽입하기 때문에(append) pop를 두번 해줬다.
        else:
            stack.pop()
            stack.pop()
print(sum(stack))

9012번: 괄호

import sys
n = int(sys.stdin.readline())

for i in range(n):
    input = sys.stdin.readline().rstrip()
    stack = [0]
    for j in input:
        if j == "(":
            stack.append(j)
        else:
            try:
                stack.pop()
            except:
                continue

    if len(stack) == 1:
        if stack[0] == "(":
            print("NO")
        else:
            print("YES")
    else:
        print("NO")

4949번: 균현잡힌 세상

import sys
input = sys.stdin.readline
while 1:
    string = input().rstrip()
    stack = []
    true_flag = 1
    for cha in string:
        if cha == '(' or cha == '[':
            stack.append(cha)
        elif cha == ')':
            if stack and stack[-1] == '(':
                stack.pop()
            else:
                true_flag = 0
                break
        elif cha == ']':
            if stack and stack[-1] == '[':
                stack.pop()
            else:
                true_flag = 0
                break
    if string == '.':
        break
    print("yes" if true_flag and not(stack) else "no")

Hello, I'm@nickhealthy
개발자를 꿈꾸고, 파이썬과 클라우드에 관심이 많은 비전공자

Github